#include "discstructuretreeview.h"

#include <QHelpEvent>
#include <QEvent>
#include <QMouseEvent>
#include <KApplication>
#include <QDesktopWidget>
#include <KLocale>

#include "kdcdiscmodel.h"
#include "movietooltip.h"
#include <kdclib.h>

#include <interfaces/kdcjobsinterface.h>
extern KDCJobsInterface *gKDCJobsInterface;
#include <interfaces/kdcstatusbarinterface.h>
extern KDCStatusBarInterface *gKDCStatusBar;
#include <interfaces/kdcframegeneratorinterface.h>
extern KDCFrameGeneratorInterface *gKDCFrameGenerator;

DiscStructureTreeView::DiscStructureTreeView( QWidget *aParent ) : QTreeView( aParent )
{
	setMouseTracking( true );
}

bool DiscStructureTreeView::viewportEvent( QEvent *aEvent )
{
	if ( aEvent->type() == QEvent::ToolTip )
	{
		QHelpEvent *event = static_cast<QHelpEvent*>( aEvent );
		QModelIndex index = indexAt( event->pos() );
		if ( fIndex != index )
			fIndex = index;
		else
			return true;
		KDCDiscModel *kdcModel = static_cast<KDCDiscModel*>( model() );
		KDCObject *obj = kdcModel->objectFromIndex( fIndex );
		if ( fToolTip )
			deletePtr( fToolTip );
		if ( obj && obj->object() == KDC::Movie )
		{
			fToolTip = new KPassivePopup( this );
			QPalette pal = fToolTip->palette();
			pal.setColor( QPalette::Window, Qt::white );
			fToolTip->setPalette( pal );
			KDCMovie *movie = static_cast<KDCMovie*>( obj );

			QString error;
			QPixmap pix = gKDCJobsInterface->getScaledThumbnail( movie->metaData()->name(), 100, error );
			if ( !error.isEmpty() )
				gKDCStatusBar->showMessage( i18n("Error during create thumbnail. ") + error, KDC::Error );
			else
			{
				pix = gKDCFrameGenerator->createFrame( "movie", pix, 0, 0, error );
				if ( !error.isEmpty() )
					gKDCStatusBar->showMessage( i18n("Error during create thumbnail. ") + error, KDC::Error );
				else
				{
					pix = gKDCFrameGenerator->createFrame( "polaroid", pix, 0, 0, error );
					if ( !error.isEmpty() )
						gKDCStatusBar->showMessage( i18n("Error during create thumbnail. ") + error, KDC::Error );
				}
			}
			MovieToolTip *info = new MovieToolTip( movie, pix, fToolTip );
			fToolTip->setView( info );
			int delta = 0;
			if ( KApplication::desktop()->availableGeometry().bottom() < event->globalPos().y() + fToolTip->height() )
				delta = fToolTip->height()/2;
			fToolTip->show( QPoint( event->globalPos().x(), event->globalPos().y() - delta ) );
		}
		return true;
	}
	return QTreeView::viewportEvent( aEvent );
}

void DiscStructureTreeView::mouseMoveEvent( QMouseEvent *aEvent )
{
	QModelIndex index = indexAt( aEvent->pos() );
	if ( ( fIndex != index ) && fToolTip )
		delete fToolTip;
	QTreeView::mouseMoveEvent( aEvent );
}
